(function() {
    var myApp = angular.module('myApp');

    myApp.run(function($rootScope) {

        $rootScope.ztree = {
            init: function($event) {
                $rootScope.ztree.obj = $event[0];
            },
            obj: null,
            sel: []
        };

        $rootScope.treeSelect = [];

    });
    //推送组织层级数据的controller
    myApp.controller("pushdataController", function($scope, $log, reqDataByAjax) {
        $scope.pushingdata=function(){
            //获得要插入的数据
            reqDataByAjax("/scheduling/api/comm/pushingdata/getorganizeData").then(function(organizedata) {
                $scope.insertorganizedata1=organizedata[0];
                $scope.insertorganizedata2=organizedata[1];
                $scope.insertorganizedata3=organizedata[2];
                reqDataByAjax("/scheduling/api/comm/pushingdata/pushorganize1",$scope.insertorganizedata1,"POST").then(function(data) {
                    reqDataByAjax("/scheduling/api/comm/pushingdata/pushorganize2",$scope.insertorganizedata2,"POST").then(function(data) {
                        reqDataByAjax("/scheduling/api/comm/pushingdata/pushorganize3",$scope.insertorganizedata3,"POST").then(function(data) {
                            alert('推送成功');
                        });
                    });
                });
            });
        };
    });
    myApp.controller("myGroupTreeController", function($scope, $log, reqDataByAjax,$rootScope) {
        // 设置用户组树结构的Option
        var url = "/scheduling/api/user/group/getall";
        function dataSource(parentGroup, callback) {
            reqDataByAjax(url, { parent_id : parentGroup.group_id })
                .then(function(data) {
                    var ret = [];
                    for (var i = 0; i < data[0].length; ++i) {
                        var item = data[0][i];
                        item['type'] = 'folder';
                        ret.push(item);
                    }
                    callback({ data: ret });
                });
        }
        $scope.option = {
            dataSource: dataSource,
            multiSelect: false,
            folderSelect: true
        };

        // 记录当前选中组
        $scope.$on('selected.fu.tree', function(event, element, e, o) {
            if (element.is('#grouptree')) {
                $scope.$root.selectedGroup = o.selected[0];

                $scope.$root.$broadcast("show.tab", "#groupusertab");
            }
        });
        $scope.$on('deselected.fu.tree', function(event, element) {
            if (element.is('#grouptree')) {
                $scope.$root.selectedGroup = null;
                $scope.$root.$broadcast("show.tab", "#helptab");
            }
        });

    });
    myApp.controller("menuTreeController", function($rootScope,$scope, $log, mtAjax) {

        // 显示初始化时
        $scope.modalShown = function($event) {

            // if($rootScope.selected.length > 0){
            //     $scope.roleName = $rootScope.selected[0].name;
            // }
            $scope.roleName = $rootScope.roleName;

            var ztree = $rootScope.ztree.obj;
            ztree && ztree.reAsyncChildNodes(null, "refresh", false);

        };

        $scope.option = {
            async: {
                enable: true,
                url: '/scheduling/api/user/group/menuselect',
                contentType: 'application/json',
                type: 'get',
                dataType: 'json',
                autoParam: ['group_id'],
                dataFilter: dataFilter
            },
            check: {
                enable: true
            },
            callback: {
                beforeAsync: beforeAsync,
                onNodeCreated: onNodeCreated,
                onClick: onClick
            },
            data: {
                key: {
                    url: '_url_'
                }
            }
        };

        function dataFilter(treeId, parentNode, data) {
            var treeNodes = [];
            var groups = data.data[0],
                items = data.data[1];
            for(var i = 0; i < groups.length; ++i) {
                var item = $.extend({
                    isParent: true
                }, groups[i]);
                treeNodes.push(item);
            }

            for(var i = 0; i < items.length; ++i) {
                var item = $.extend({
                    isParent: false
                }, items[i]);
                // 默认选中
                for(var j = 0; j < $rootScope.treeSelect.length; j++) {
                    if($rootScope.treeSelect[j].group_id == items[i].group_id) {
                        item.checked = 1;
                        break;
                    }

                }
                treeNodes.push(item);
            }
            return treeNodes;
        }

        function beforeAsync(treeId, treeNode) {
            var ztree = $rootScope.ztree.obj;
            if(!ztree)
                return true;

            // var role_id = null;
            // var roleSel = $rootScope.roleTable.sel;
            // if(roleSel && roleSel.length)
            //  role_id = roleSel[0].role_id;

            // var system_id = $rootScope.system.sel;
            // if($rootScope.selected.length > 0){
            //     ztree.setting.async.otherParam = {
            //         role_id: $rootScope.selected[0].role_id
            //     };
            // }

            if($rootScope.roleId ){
                ztree.setting.async.otherParam = {role_id: $rootScope.roleId};
            }


            return true;
        }

        function onNodeCreated(event, treeId, treeNode) {
            var ztree = $rootScope.ztree.obj;
            if(!ztree)
                return;

            ztree.expandNode(treeNode, true);
        }

        function onClick(event, treeId, treeNode, clickFlag) {
            var ztree = $rootScope.ztree.obj;
            if(!ztree)
                return;

            ztree.checkNode(treeNode, undefined, true, true);
        }

        // 保存选择
        $scope.ok = function() {
            // var role_id = $rootScope.roleTable.sel[0].role_id;
            $rootScope.treeSelect = $rootScope.ztree.sel;

            for(var i=0;i<$rootScope.ztree.sel.length;i++){
                // $rootScope.treeSelect[i] = angular.extend($rootScope.treeSelect[i], { role_id: $scope.$root.selected[0].role_id })
                $rootScope.treeSelect[i] = angular.extend($rootScope.treeSelect[i], { group_id1: $rootScope.roleId})

            }

            // if($rootScope.treeSelect.length > 0)
            //     $rootScope.selectUsers = "已选择";

            //
            mtAjax("/scheduling/api/user/group/saveRoleMenus", $rootScope.treeSelect, 'POST').then(function (ret) {
                alert('保存成功！');
                $rootScope.treeSelect=[];
                // mtRefreshTable("#tablelist");
            },function (ret) {
                alert('保存失败！');
            });

        };

        $scope.cancel = function() {
            $rootScope.treeSelect = [];

        };

    });
    myApp.controller("createGroupController", function($scope, $log, reqDataByAjax) {
        // TAB显示前初始化显示内容
        $scope.$on("show.bs.tab", function(event, element, target) {
           if (target.is("#creategroup")) {
               $scope.group = {};
           }
        });

        // 调用服务创建用户组
        var url = "/scheduling/api/user/group/creategroup";
        $scope.ok = function() {
            var group = $scope.group;
            group.parent_id = $scope.$root.selectedGroup && $scope.$root.selectedGroup.group_id;
            group.sort = +group.sort;
            reqDataByAjax(url, group, 'POST').then(function() {
                // 刷新树显示
                if (group.parent_id)
                    $scope.$root.$broadcast("refreshFolder.tree", "#grouptree");
                else
                    $scope.$root.$broadcast("refresh.tree", "#grouptree");
            });
        };
    });
    myApp.controller("modifyGroupController", function($scope, $log, reqDataByAjax) {
        // TAB显示前初始化显示内容
        $scope.$on("show.bs.tab", function(event, element, target) {
            if (target.is("#modifygroup")) {
                $scope.group = $scope.$root.selectedGroup;
            }
        });
        // 调用服务修改用户组
        var url = "/scheduling/api/user/group/modifygroup";
        $scope.ok = function() {
            $scope.group.sort = +$scope.group.sort;
            reqDataByAjax(url, $scope.group, "POST").then(function() {
               $scope.$root.$broadcast("updateItem.tree", "#grouptree", $scope.group);
            });
        };
    });
    myApp.controller("deleteGroupController", function($scope, $log, reqDataByAjax) {
        // 调用服务删除用户组
        var url = "/scheduling/api/user/group/deletegroup";
        $scope.ok = function() {
            var group = $scope.$root.selectedGroup;
            reqDataByAjax(url, group, "POST").then(function() {
                if (group.parent_id)
                    $scope.$root.$broadcast("refreshParentFolder.tree", "#grouptree");
                else
                    $scope.$root.$broadcast("refresh.tree", "#grouptree");
            });
        };
    });
    myApp.controller("myGroupUserTableController", function($scope, $log, myGroupUserTableOption, reqDataByAjax,$rootScope,mtShowModal,$compile) {
        // 设置组用户列表Option
        var url = "/scheduling/api/user/group/allgroupusers";
        $scope.option = myGroupUserTableOption;
        $scope.option.ajax = ajax;
        $scope.option.rowCallback = function(row, data, index) {
            $compile(angular.element(row))($scope);
        };
        function ajax(data, callback, settings) {
            data.group_id = $scope.$root.selectedGroup && $scope.$root.selectedGroup.group_id;
            reqDataByAjax(url, data).then(function (ret) {
                $scope.userlist=ret[0];
                callback({
                    "draw": data.draw,
                    "recordsTotal": ret[1][0].recordsTotal,
                    "recordsFiltered": ret[2][0].recordsFiltered,
                    "data": ret[0]
                });
                $('#selectall').prop('checked',false);
                $('#groupusertable tbody tr ').removeClass('selected');
                $scope.if_all=true;
                for(var i=0;i<$scope.userlist.length;i++){
                    if($scope.userlist[i].selected==1){
                        $('#groupusertable tbody tr').eq(i).addClass('selected');
                    }else{
                        $scope.if_all=false;
                    }
                }
                if($scope.if_all){
                    $('#selectall').prop('checked',true);
                }
            });
        }

        $scope.changeUsers=function(e){
            var index=e;
            if(!$('#groupusertable tbody tr').eq(index).hasClass("selected")){
                $('#groupusertable tbody tr ').eq(index).addClass('selected');
                $('#groupusertable tbody tr input').eq(index).prop('checked',true);
                for(var i=0;i<$('#groupusertable tbody tr input').length;i++){
                    if($('#groupusertable tbody tr input').eq(i).prop('checked')){
                        continue;
                    }else{
                        $('#selectall').prop('checked',false);
                        return;
                    }
                }
                $('#selectall').prop('checked',true);
            }else{
                $('#groupusertable tbody tr ').eq(index).removeClass('selected');
                $('#groupusertable tbody tr input').eq(index).prop('checked',false);
                for(var i=0;i<$('#groupusertable tbody tr input').length;i++){
                    if($('#groupusertable tbody tr input').eq(i).prop('checked')){
                        continue;
                    }else{
                        $('#selectall').prop('checked',false);
                        return;
                    }
                }
                $('#selectall').prop('checked',true);
            }
        };
        // TAB显示时刷新组用户列表
        $scope.$on("shown.bs.tab", function(event, element, target) {
            if (target.is("#groupusertab"))
                $scope.$root.$broadcast("refresh.table", "#groupusertable");
        });
        // 记录组用户选中情况
        $scope.$root.selectedGroupUsers = [];
        $scope.$on("select", function(event, element, e, dt, type, indexes) {
            if (element.is("#groupusertable"))
                $scope.$root.selectedGroupUsers = Array.prototype.slice.call(dt.rows('.selected').data(), 0);
        });
        $scope.$on("deselect", function(event, element, e, dt, type, indexes) {
            if (element.is("#groupusertable"))
                $scope.$root.selectedGroupUsers = Array.prototype.slice.call(dt.rows('.selected').data(), 0);
        });
        $scope.$on("draw.dt", function(event, element, e, settings) {
            if (element.is("#groupusertable"))
                $scope.$root.selectedGroupUsers = [];
        });
        $scope.setMenus = function() {
            $rootScope.roleId =  $scope.$root.selectedGroup.group_id;
            $rootScope.roleName = $scope.$root.selectedGroup.name;
            mtShowModal("#menuTreeModal");
        };
        $scope.selectAll=function(){
            console.log($('#selectall').prop('checked'));
            if( $('#selectall').prop('checked')){
                for(var i=0;i<$('#groupusertable tbody tr input').length;i++){
                    $('#groupusertable tbody tr input').eq(i).prop('checked',true);
                    $('#groupusertable tbody tr').eq(i).addClass("selected");
                }
            }else{
                for(var i=0;i<$('#groupusertable tbody tr input').length;i++){
                    $('#groupusertable tbody tr input').eq(i).prop('checked',false);
                    $('#groupusertable tbody tr').eq(i).removeClass("selected");
                }
            }
        };
        $scope.saveuserlist=function(){
            $scope.selectUser = [];
            for (var i = 0; i < $('#groupusertable tbody tr input').length; i++) {
                if ($('#groupusertable tbody tr input').eq(i).prop('checked')) {
                    var params = {
                        user_id: $scope.userlist[i].user_id,
                        group_id:$scope.$root.selectedGroup.group_id
                    };
                    $scope.selectUser.push(params);
                }
            }
            var param={
                group_id:$scope.$root.selectedGroup.group_id
            };
            reqDataByAjax('/scheduling/api/user/group/cleargroupusers', param, 'POST').then(function (ret) {
                if($scope.selectUser.length>0){
                    reqDataByAjax('/scheduling/api/user/group/savegroupusers',$scope.selectUser, 'POST').then(function (ret) {
                        alert('保存成功！');
                    });
                }else{
                    alert('保存成功！')
                }

            });
        };
    });
    myApp.controller("addGroupUsersController", function($scope, $log, candidateUsersTableOption, reqDataByAjax) {
        // 设置候选用户表Option
        $scope.option = candidateUsersTableOption;
        $scope.option.ajax = ajax;
        function ajax(data, callback, settings) {
            var url = "/scheduling/api/user/group/allcandidateusers";
            data.group_id = $scope.$root.selectedGroup && $scope.$root.selectedGroup.group_id;
            reqDataByAjax(url, data).then(function (ret) {
                callback({
                    "draw": data.draw,
                    "recordsTotal": ret[1][0].recordsTotal,
                    "recordsFiltered": ret[2][0].recordsFiltered,
                    "data": ret[0]
                });
            });
        }
        // TAB显示时刷新候选用户列表
        $scope.$on("shown.bs.tab", function(event, element, target) {
            if (target.is("#addusertab"))
                $scope.$root.$broadcast("refresh.table", "#addusertable");
        });
        // 记录候选用户选中情况
        $scope.$root.selectedAddUsers = [];
        $scope.$on("select", function(event, element, e, dt, type, indexes) {
            if (element.is("#addusertable"))
                $scope.$root.selectedAddUsers = Array.prototype.slice.call(dt.rows('.selected').data(), 0);
        });
        $scope.$on("deselect", function(event, element, e, dt, type, indexes) {
            if (element.is("#addusertable"))
                $scope.$root.selectedAddUserss = Array.prototype.slice.call(dt.rows('.selected').data(), 0);
        });
        $scope.$on("draw.dt", function(event, element, e, settings) {
            if (element.is("#addusertable"))
                $scope.$root.selectedAddUsers = [];
        });

        // 调用服务添加用户进用户组
        $scope.ok = function() {
            var url = "/scheduling/api/user/group/addgroupusers";
            var group = $scope.$root.selectedGroup;
            var users = $scope.$root.selectedAddUsers;
            for (var u in users)
                users[u].group_id = group.group_id;
            reqDataByAjax(url, users, "POST");
        };
    });
    myApp.controller("removeGroupUsersController", function($scope, $log, reqDataByAjax) {
        // 调用服务从用户组移除用户
        $scope.ok = function() {
            var url = "/scheduling/api/user/group/removegroupusers";
            var group = $scope.$root.selectedGroup;
            var users = $scope.$root.selectedGroupUsers;
            for (var u in users)
                users[u].group_id = group.group_id;
            reqDataByAjax(url, users, "POST").then(function() {
                $scope.$root.$broadcast("refresh.table", "#groupusertable");
            });
        };
    });

})();

